package com.cetc;

import org.junit.Test;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;

/**
 * @Classname UrlConnectionTest
 * @Description URL网络编程
 * @Date 2022/11/26 16:52
 * @Created by louzhuangxi
 */
public class UrlConnectionTest {
    @Test
    public void test01() throws MalformedURLException {
        URL url = new URL("http://localhost:1024/static/js/app.js");
        System.out.println(url.getProtocol());
        System.out.println(url.getPort());
        System.out.println(url.getHost());
        System.out.println(url.getQuery());
        System.out.println(url.getFile());
        System.out.println(url.getPath());
    }

    @Test
    public void test02() {
        FileOutputStream fos = null;
        InputStream is = null;
        URLConnection urlConnection;
        try {
            URL url = new URL("http://localhost:1024/static/js/app.js");
            urlConnection = url.openConnection();
            urlConnection.connect();
            is = urlConnection.getInputStream();
            fos = new FileOutputStream("data/1.js");
            int len;
            byte[] data = new byte[1024];
            while ((len = is.read(data)) != -1) {
                fos.write(data, 0, len);
            }
            System.out.println(urlConnection.getContentType());
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }
                if (fos != null) {
                    fos.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

    }
}
